package com.fsz.pachong.pachong.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

public class FileUtil {

    public static int FILEBYTE = (1024 * 200);

    /**
     * 文件写入（追加）
     * @throws IOException
     */
    public static boolean writePVFile(String filePath, String fileName, String suffix,
                                      Map<String, List<String>> contentsMap) throws IOException {
        try {

            File fileDir = new File(filePath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file = new File(filePath, fileName + suffix);
            FileWriter fileWriter = new FileWriter(file, true);
            BufferedWriter writer = new BufferedWriter(fileWriter);
            if (contentsMap != null && contentsMap.size() > 0) {

                Object[] keySet = contentsMap.keySet().toArray();
                for (Object param : keySet) {
                    List<String> value = contentsMap.get(param);
                    if (value != null && contentsMap.size() > 0) {
                        for (int i = 0; i < value.size(); i++) {
                            String content = value.get(i);
                            if (!StringUtils.isEmpty(content))
                                writer.write(content + "\r\n");
                        }
                    }
                }
            }
            writer.flush();
            writer.close();
            fileWriter.close();
            return true;
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }

    }

    /**
     * 复制单个文件
     *
     * @param oldPathFile
     *            准备复制的文件源
     * @param newPathFile
     *            拷贝到新绝对路径带文件名
     * @return
     * @throws IOException
     */
    public static boolean copyFile(File oldPathFile, String dir, String newPathFile) throws IOException {

        int bytesum = 0;
        int byteread = 0;

        if (!oldPathFile.exists()) // 文件存在时
            return false;

        if (!createDirectory(dir))
            return false;

        InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件

        FileOutputStream fs = new FileOutputStream(newPathFile);
        byte[] buffer = new byte[FILEBYTE];
        while ((byteread = inStream.read(buffer)) != -1) {
            bytesum += byteread; // 字节数 文件大小
            fs.write(buffer, 0, byteread);
        }
        fs.flush();
        fs.close();
        inStream.close();
        return true;
    }

    /**
     * 删除文件
     *
     * @param path
     */
    public static void deldeteFile(String path) {
        try {
            File file = new File(path);
            if (file.exists())
                file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文本文件 返回内容
     *
     * @param filePath
     * @return
     */
    public static List<String> readTxtFile(String filePath) {

        List<String> result = new ArrayList<String>();
        File file = new File(filePath);
        if (!file.exists()) {
            return result;
        }
        BufferedReader bf = null;
        FileInputStream fileInpustream = null;
        InputStreamReader inputStreamReader = null;
        try {
            fileInpustream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInpustream);
            bf = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = bf.readLine()) != null) {
                if (!StringUtils.isEmpty(line))
                    result.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bf != null) {
                    bf.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (fileInpustream != null) {
                    fileInpustream.close();
                }

            } catch (Exception e) {
            }
        }
        return result;
    }

    /**
     * 获取后缀
     *
     * @param pictype
     * @return
     */
    public static String getSuffix(String name) {

        if (name.contains("."))
            return name.substring(name.lastIndexOf(".") + 1, name.length());
        else
            return name;
    }

    /**
     * 获取没有后缀的文件名
     *
     * @param pictype
     * @return
     */
    public static String getFileNameExcludeSuffix(String name) {

        if (name.contains("."))
            return name.substring(0, name.lastIndexOf("."));
        else
            return name;
    }

    /**
     * 创建文件夹
     *
     * @param Directory
     * @return
     */
    public static boolean createDirectory(String Directory) {

        File directory = new File(Directory);
        if (!directory.exists()) {
            if (directory.mkdirs())
                return true;
        }
        return true;

    }

    /**
     * 获取静态资源文件夹（这个项目assets目录是不需要验证的，不安全，其他路径是可以的）
     *
     * @return
     */
    /*
     * public static String getCrmBasePath() {
     *
     * return crmBasePath; }
     */

    /**
     * 获取静态资源文件夹（这个项目assets目录是不需要验证的，不安全，其他路径是可以的）
     *
     * @return
     */
    public static String getSystemStaticPath() {
        try {
            return ResourceUtils.getURL("classpath:static").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取项目根目录
     *
     * @return
     */
    public static String getSystemRootPath() {
        try {
            return ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void readFileName(String dirPath) {
        try {

            File file = new File(dirPath);
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(dirPath + "/" + filelist[i]);
                if (!readfile.isDirectory()) {
                    String fileName = readfile.getName().substring(0, readfile.getName().indexOf("."));
                    System.out.println("\"" + fileName + "\"" + ",");

                } else if (readfile.isDirectory()) {
                    // readFileXml(dirPath + "/" + filelist[i], result);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的文件
     *
     * @param dirPath
     * @param result
     */
    public static void readExcelFile(String dirPath, List<File> result) {
        try {

            File file = new File(dirPath);
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(dirPath + "/" + filelist[i]);
                if (!readfile.isDirectory()) {
                    result.add(readfile);
                } else if (readfile.isDirectory()) {
                    readExcelFile(dirPath + "/" + filelist[i], result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取远程文件
     * @param in_st
     * @param charset
     * @param path
     * @param fileName
     * @return
     * @throws IOException
     */
    public static File InputStreamFile(InputStream in_st, String charset, String path, String fileName) throws IOException {
        FileUtil.createDirectory(path);
        File file = new File(path+File.separator+fileName);
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = in_st.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        outputStream.write(bos.toByteArray());
        outputStream.flush();
        bos.close();
        outputStream.close();
        return file;
    }

}
